package com.mall.pay.services;

import com.mall.order.OrderCoreService;
import com.mall.order.dto.PayOrderSuccessRequest;
import com.mall.order.dto.PayOrderSuccessResponse;
import com.mall.pay.PayCoreService;
import com.mall.pay.constants.PayChannelEnum;
import com.mall.pay.constants.PayResultEnum;
import com.mall.pay.constants.PayReturnCodeEnum;
import com.mall.pay.dal.entitys.Payment;
import com.mall.pay.dal.persistence.PaymentMapper;
import com.mall.pay.dto.PaymentRequest;
import com.mall.pay.dto.alipay.AlipayQueryRetResponse;
import com.mall.pay.dto.alipay.AlipaymentResponse;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import javax.validation.constraints.NotBlank;
import java.util.Date;

@Service
public class PayCorServiceImpl implements PayCoreService {

    @Autowired
    PayHelper payHelper;

    @Reference(timeout = 3000, check = false)
    OrderCoreService orderCoreService;

    @Autowired
    private PaymentMapper paymentMapper;

    @Override
    public AlipaymentResponse aliPay(PaymentRequest request) {

        AlipaymentResponse response = new AlipaymentResponse();
        // 1. 携帶相关的支付信息，去支付宝后台，请求支付二维码
        String fileName = payHelper.test_trade_precreate(request);
        if (fileName == null) {
            // 2. 如果没有获取到支付二维码，直接返回支付失败
            //  return 响应  GET_CODE_FALIED
            response.setCode(PayReturnCodeEnum.GET_CODE_FALIED.getCode());
            response.setMsg(PayReturnCodeEnum.GET_CODE_FALIED.getMsg());
            return response;
        }
        // 3. 如果能获取支付二维码，在tb_payment插入一条支付记录(支付中)
        Date createTime = new Date();
        Payment payment = new Payment(null, PayResultEnum.PAY_PROCESSING.getCode(), request.getTradeNo(), request.getSubject(), request.getTotalFee(), null, request.getUserId(), request.getUsername(), request.getOrderFee(), request.getPayChannel(), null, null, "支付宝支付", createTime, createTime);
        paymentMapper.insertSelective(payment);

        // 4. 返回获取到的支付二维码
        String qrCode = "http://127.0.0.1:8080/image/" + fileName;
        response.setQrCode(qrCode);
        response.setCode(PayReturnCodeEnum.SUCCESS.getCode());
        response.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());
        return response;
    }

    @Override
    public AlipayQueryRetResponse queryAlipayRet(PaymentRequest request) {
        AlipayQueryRetResponse response = new AlipayQueryRetResponse();

        String orderId = request.getTradeNo();
        boolean payResult = payHelper.test_trade_query(orderId);

        Example example = new Example(Payment.class);
        example.createCriteria().andEqualTo("orderId", orderId);
        Date date = new Date();
        Payment payment = new Payment();

        if (payResult) {
            // 1. 修改tb_payment支付状态(支付成功)
            String code = PayResultEnum.PAY_SUCCESS.getCode();
            payment.setStatus(code);
            payment.setPaySuccessTime(date);
            payment.setUpdateTime(date);
            paymentMapper.updateByExampleSelective(payment, example);
            //   调用订单服务的接口方法去完成的功能
            // 2. 修改订单状态为已支付
            // 3. 扣减锁定库存(根据订单中的订单商品条目的数量)
            PayOrderSuccessRequest payOrderSuccessRequest = new PayOrderSuccessRequest();
            payOrderSuccessRequest.setOrderId(orderId);
            orderCoreService.payOrderSuccess(payOrderSuccessRequest);
            // 4. 返回支付成功的响应
            response.setCode(PayReturnCodeEnum.SUCCESS.getCode());
            response.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());
        } else {
            // 1. 修改tb_payment中的支付状态(支付失败)
            payment.setStatus(PayResultEnum.PAY_FAIL.getCode());
            payment.setUpdateTime(date);
            payment.setCompleteTime(date);
            paymentMapper.updateByExampleSelective(payment, example);
            // 2. 返回支付失败的响应
            response.setCode(PayReturnCodeEnum.PAYMENT_PROCESSOR_FAILED.getCode());
            response.setMsg(PayReturnCodeEnum.PAYMENT_PROCESSOR_FAILED.getMsg());
        }
        return response;
    }
}
